# -*- coding:utf8 -*-
import json
import datetime
import random

import hashlib
import urllib
import urllib2
from django.http.response import HttpResponseRedirect
import time
from wanpuzzle.models.common import Application
from wanpuzzle.models.bengbengtiao import BengVersion, BengPackage, BengProgram, \
    BengUserData, BengProgramUserData, BengShared, BengSharedLike, BengActivityLike, BengActivity
from wanpuzzle.models.common import Subject
from wanbatvapp import settings


from wanbatvapp.http.whttp import send_error_response_with_message, \
    send_error_response_on_exception, send_ok_response_with_data, send_ok_response_with_list, \
    send_response_with_result

__author__ = 'Forcs'

HD = 720
FHD = 1080
UHD = 2160


def get_program_list(request, stb_id=None):
    """
    获取节目列表
    :param stb_id: 设备id
    """
    if not stb_id:
        return send_error_response_with_message('设备id为空')
    try:
        user = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        return send_error_response_on_exception(e)

    if not user:
        return send_error_response_with_message('无此用户')

    body = request.POST

    dpi = int(body["dpi"])
    res_postfix = 'hd'
    if dpi == FHD or dpi == UHD:
        res_postfix = 'fhd'

    try:
        program_qs = BengProgram.objects.filter(is_invalid=False, need_pay=False)  # 添加需要支付过滤
        if program_qs:
            # 获取解锁清单
            unlock_items = user.unlock_programs.split(",") if user.unlock_programs.find(",") else []
            # 获取用户的个人数据，比如节目的星星个数，节目是否收藏
            program_user_list = list()
            try:
                program_user_qs = BengProgramUserData.objects.filter(user_data=user)
                if program_user_qs and program_user_qs.count():
                    for program_user in program_user_qs.iterator():
                        program_user_list.append({
                            "token": program_user.program.token,
                            "rating": program_user.rating,
                            "isCollect": program_user.is_collected
                        })
            except:
                pass

            program_list = list()
            for program in program_qs:
                user_data = {
                    "rating": 0,
                    "isCollect": False,
                }

                if program_user_list:
                    for item in program_user_list:
                        if item["token"] == program.token:
                            user_data["rating"] = item["rating"]
                            user_data["isCollect"] = item["isCollect"]
                            break

                program_list.append({
                    "title": program.title,
                    "token": program.token,
                    "coverNormalForeground": getattr(program, "cover_n_" + res_postfix, ''),
                    "coverHighlightForeground": getattr(program, "cover_h_fg_" + res_postfix, ''),
                    "coverHighlightBackground": getattr(program, "cover_h_bg_" + res_postfix, ''),
                    "bgm": program.bgm,
                    "media": program.media,
                    "isUnlock": program.token in unlock_items,
                    "rating": user_data["rating"],
                    "isCollect": user_data["isCollect"],
                    "contentCode": program.token,
                    "categoryCode": "301",
                    "isPay": True
                })
            return send_ok_response_with_list(program_list)
        else:
            return send_error_response_with_message("节目为空")
    except Exception as e:
        return send_error_response_on_exception(e)


def get_pay_program_list(request, stb_id=None):
    """
    获取付费节目列表
    :param request:
    :param std_id:设备id
    :return:
    """
    host = request.get_host()
    if not stb_id:
        return send_error_response_with_message('设备id为空')
    try:
        user = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        return send_error_response_on_exception(e)
    if not user:
        return send_error_response_with_message('无此用户')

    try:
        program_qs = BengProgram.objects.filter(is_invalid=False, need_pay=True)
        if program_qs:
            # 获取用户数据
            program_user_list = list()
            try:
                program_user_qs = BengProgramUserData.objects.filter(user_data=user)
                if program_user_qs and program_user_qs.count():
                    for program_user in program_user_qs.iterator():
                        program_user_list.append({
                            "token": program_user.program.token,
                            "rating": program_user.rating,
                            "isCollect": program_user.is_collected
                        })
            except:
                pass
            program_list = list()
            for program in program_qs:
                user_data = {
                    "rating": 0,
                    "isPay": False,
                    "isCollect": False
                }
                if program_user_list:
                    for item in program_user_list:
                        if item["token"] == program.token:
                            user_data["rating"] = item["rating"]
                            user_data["isCollect"] = item["isCollect"]
                            break
                # subject = program.subject
                # user_data["isPay"] = _is_pay(host, stb_id, subject.code)
                user_data["isPay"] = _check_pay(host, stb_id, program.token)

                program_list.append({
                    "title": program.title,
                    "token": program.token,
                    "coverNormalForeground": getattr(program, "cover_n_" + 'hd', ''),
                    "coverHighlightForeground": getattr(program, "cover_h_fg_" + 'hd', ''),
                    "coverHighlightBackground": getattr(program, "cover_h_bg_" + 'hd', ''),
                    "bgm": program.bgm,
                    "isUnlock": True,
                    "isCollect": user_data["isCollect"],
                    "rating": user_data["rating"],
                    "media": program.media,
                    "isPay": user_data["isPay"],
                    "contentCode": program.token,
                    "categoryCode": "302",
                })
            return send_ok_response_with_list(program_list)
        else:
            return send_error_response_with_message('节目为空')
    except Exception as e:
        return send_error_response_on_exception(e)


def is_pay(request, stb_id, program_token):
    """
    判断用户是否付费
    :param request:
    :param stb_id:
    :param program_token:
    :return:
    """
    host = request.get_host()
    # try:
    #     program = BengProgram.objects.get(token=program_token)
    # except Exception as e:
    #     return send_error_response_on_exception(e)
    # subject_id = program.subject.code
    #
    # app = Application.objects.get(app_id='bengbengtiao')
    # app_token = app.token
    #
    # # 调用鉴权接口
    # req = urllib2.Request('http://%s/api/common/wpay/check/%s?userid=%s&subjectcode=%s' % (host, app_token, stb_id, subject_id))
    # res = urllib2.urlopen(req)
    # res_concent = res.read()
    # res.close()
    #
    # s = json.loads(res_concent)
    # paycompleted = s["data"]["payCompleted"]
    paycompleted = _check_pay(host, stb_id, program_token)
    return send_ok_response_with_data({
        "payCompleted": str(paycompleted)
    })


def _check_pay(host, stb_id, program_token):
    """
    :param host:初始化时使用
    :param stb_id: 初始化时使用
    :param program_token: 节目token
    :return: True表示已支付，False表示未支付
    """
    if not stb_id:
        return send_error_response_with_message('设备id为空')
    if not program_token:
        return send_error_response_with_message('节目为空')
    if not host:
        return send_error_response_with_message('请求问题')

    # try:
    user = BengUserData.objects.get(stb_id=stb_id)
    payed_programs = user.payed_programs
    new_programs = list()
    if payed_programs == '0000':
        programs = BengProgram.objects.filter(is_invalid=False, need_pay=True)
        for program in programs:
            subject = program.subject
            pay_result, newexpiretime = _is_pay(host, stb_id, subject.code)
            if pay_result:
                expiretime_array = time.strptime(newexpiretime, "%Y-%m-%d %H:%M:%S")
                newexpiretime = time.strftime("%Y%m%d%H%M%S", expiretime_array)
                new_programs.append(program.token + newexpiretime)
        user.payed_programs = ','.join(new_programs)
        user.save()
        return _check_pay(host, stb_id, program_token)

    else:
        payed_programs = payed_programs.split(',')
        for payed_program in payed_programs:
            if program_token == payed_program[0:32]:
                expiretime = payed_program[32:]
                expiretime = int(expiretime)
                now = datetime.datetime.now()
                now = now.strftime("%Y%m%d%H%M%S")
                now = int(now)
                if expiretime >= now:
                    return True
                else:
                    program = BengProgram.objects.get(token=program_token)
                    subject = program.subject
                    pay_result, newexpiretime = _is_pay(host, stb_id, subject.code)
                    if pay_result:
                        expiretime_array = time.strptime(newexpiretime, "%Y-%m-%d %H:%M:%S")
                        newexpiretime = time.strftime("%Y%m%d%H%M%S", expiretime_array)
                        for new_program in payed_programs:
                            if program_token == new_program[0:32]:
                                new_programs.append(program_token + newexpiretime)
                            else:
                                new_programs.append(new_program)
                        user.payed_programs = ','.join(new_programs)
                        user.save()
                        return True
                    else:
                        for new_program in payed_programs:
                            if program_token != new_program[0:32]:
                                new_programs.append(new_program)

                        user.payed_programs = ','.join(new_programs)
                        user.save()
                        return False
        return False

    # except Exception as e:
    #     return send_error_response_on_exception(e)


def _is_pay(host, stb_id, subject_id):
    """
    判断节目是否已经付费
    :param stb_id:
    :param subject_code:
    :return:
    """
    if not stb_id:
        return send_error_response_with_message('设备id为空')
    if not subject_id:
        return send_error_response_with_message('付费节目为空')

    app = Application.objects.get(app_id='bengbengtiao')
    app_token = app.token

    # 调用鉴权接口
    req = urllib2.Request('http://%s/api/common/wpay/check/%s?userid=%s&subjectcode=%s' % (host, app_token, stb_id, subject_id))
    res = urllib2.urlopen(req)
    res_concent = res.read()
    res.close()

    s = json.loads(res_concent)
    if s["data"]["payCompleted"]:
        return s["data"]["payCompleted"], s["data"]["expiretime"]
    else:
        return s["data"]["payCompleted"], "0000-00-00 00:00:00"


def get_subject(request, program_token):
    """
    获取节目对应的包
    :param request:
    :param program_token:节目token
    :return:
    """
    if not program_token:
        return send_error_response_with_message("没有节目")
    try:
        program = BengProgram.objects.get(token=program_token)
    except Exception as e:
        return send_error_response_on_exception(e)

    if not program:
        return send_error_response_with_message("没有付费节目包")

    subject = program.subject

    return send_ok_response_with_data({
        "subject": subject.name,
        "subjectId": subject.code,
        "type": subject.type,
        "price": '%.2f' % (float(subject.price)/100),
        "application": subject.application_id
    })


def get_random_program(request, stb_id=None):
    """
    获取用户随机节目
    :param request:
    :param stb_id:设备id
    :return:
    """
    host = request.get_host()
    if not stb_id:
        return send_error_response_on_exception('设备id为空')

    try:
        user = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        return send_error_response_on_exception(e)

    if not user:
        return send_error_response_with_message('无此用户 %s' % stb_id)

    try:
        random_program_list = list()
        program_qs = BengProgram.objects.filter(is_invalid=False)
        if program_qs:
            items = BengProgramUserData.objects.filter(user_data=user, rating=3)
            for program in program_qs:
                if _is_unlocked(stb_id, program.token) or program.need_pay is True:
                    for item in items:
                        if program.token == item.program.token:
                            continue
                    random_program_list.append(program)

            if not random_program_list:
                for item in items:
                    random_program_list.append(item.token)

            random_program_count = len(random_program_list)
            random_program = random_program_list[random.randint(0, random_program_count-1)]
            user_data = {
                "rating": 0,
                "isCollect": False,
                "isPay": True,
                "categoryCode": "301",
            }

            random_items = BengProgramUserData.objects.filter(program=random_program, user_data=user)
            if random_items:
                for random_item in random_items:
                    user_data["rating"] = random_item.rating
                    user_data["isCollect"] = random_item.is_collected
            # subject = random_program.subject

            if random_program.need_pay:
                # user_data["isPay"] = _is_pay(host, stb_id, subject.code)
                user_data["isPay"] = _check_pay(host, stb_id, random_program.token)
                user_data["categoryCode"] = "302"

            return send_ok_response_with_data({
                "title": random_program.title,
                "token": random_program.token,
                "coverNormalForeground": getattr(random_program, "cover_n_" + 'hd', ''),
                "coverHighlightForeground": getattr(random_program, "cover_h_fg_" + 'hd', ''),
                "coverHighlightBackground": getattr(random_program, "cover_h_bg_" + 'hd', ''),
                "bgm": random_program.bgm,
                "isPay": user_data["isPay"],
                "media": random_program.media,
                "rating": user_data["rating"],
                "isCollect": user_data["isCollect"],
                "contentCode": random_program.token,
                "categoryCode":  user_data["categoryCode"],
            })
        else:
            return send_error_response_with_message('节目为空')
    except Exception as e:
        return send_error_response_on_exception(e)


def get_payed(request, stb_id=None):
    """
    获取已购买列表
    :param request:
    :param stb_id:
    :return:
    """
    host = request.get_host()
    print host
    if not stb_id:
        return send_error_response_with_message("设备id为空")

    try:
        user = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        return send_error_response_on_exception(e)

    if not user:
        return send_error_response_with_message("无此用户{stbid}".format(stbid=stb_id,))

    try:
        # 获取付费节目
        pay_programs = BengProgram.objects.filter(need_pay=True)
        pay_programs_list = list()
        for pay_program in pay_programs:
            pay_item = BengProgramUserData(program=pay_program, user_data=user)
            # subject = pay_program.subject
            # if _is_pay(host=host, subject_id=subject.code, stb_id=stb_id):
            if _check_pay(host, stb_id, pay_program.token):
                pay_programs_list.append({
                    "token": pay_program.token,
                    "title": pay_program.title,
                    "media": pay_program.media,
                    "rating": pay_item.rating,
                    "contentCode": pay_program.token,
                    "categoryCode": "302",
                    "isPay": True,
                    "isCollect": pay_item.is_collected,
                })
        return send_ok_response_with_list(pay_programs_list)
    except Exception as e:
        return send_error_response_on_exception(e)


def get_favorite(request, stb_id=None):
    """
    获取收藏列表
    :param stb_id: 设备id
    """
    host = request.get_host()
    if not stb_id:
        return send_error_response_with_message('设备id为空')

    try:
        user = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        return send_error_response_on_exception(e)

    if not user:
        return send_error_response_with_message('无此用户 %s' % stb_id)

    try:
        user_favorite = BengProgramUserData.objects.filter(user_data=user, is_collected=True)
        if user_favorite.count() == 0:
            return send_ok_response_with_list([], message='无收藏内容')
        fav_list = list()

        for favorite_item in user_favorite:
            program_data = {
                "isPay": True,
                "categoryCode": "301",
            }
            program = favorite_item.program
            if program.need_pay:
                # subject = program.subject
                # program_data["isPay"] = _is_pay(host, stb_id, subject.code)
                program_data["isPay"] = _check_pay(host, stb_id, program.token)
                program_data["categoryCode"] = "302"

            fav_list.append({
                "token": program.token,
                "title": program.title,
                "media": program.media,
                "rating": favorite_item.rating,
                "contentCode": program.token,
                "categoryCode": program_data["categoryCode"],
                "isPay": program_data["isPay"],
                "isCollect": True,
            })
        return send_ok_response_with_list(fav_list)
    except Exception as e:
        return send_error_response_on_exception(e)


def get_user_data(request, stb_id=None):
    """
    获取用户数据，总的星星个数，微信信息（如果已经绑定了设备的话）
    :param stb_id: 设备id
    """
    try:
        user_data = BengUserData.objects.get(stb_id=stb_id)
        return send_ok_response_with_data({
            "stbId": stb_id,
            "ratingTotal": user_data.rating_total,
            "wxUserId": user_data.wx_user_id if user_data.wx_user_id else "",
            "wxNickname": user_data.wx_nickname if user_data.wx_nickname else "",
            "wxAvatar": user_data.wx_avatar if user_data.wx_avatar else "",
            "unlocks": user_data.unlock_programs if user_data.unlock_programs else ""
        })
    except Exception as e:
        return send_error_response_on_exception(e)


def get_program(request, program_token=None):
    """
    获取节目视频流
    :param program_token: 节目标识
    """
    params = urllib.urlencode(request.GET)
    try:
        program = BengProgram.objects.get(token=program_token)
        return HttpResponseRedirect("http://%s%s?%s" % (settings.WANBATV_CDN_URL, program.media, params))
    except Exception as e:
        return send_error_response_on_exception(e)


def get_program_user_data(request, program_token=None):
    """
    获取节目的用户数据，星星个数，是否收藏
    :param program_token: 节目标识
    """
    body = request.POST
    stb_id = body["stbid"]

    try:
        program_user = _get_program_user_data(program_token=program_token, stb_id=stb_id)
        send_ok_response_with_data({
            "token": program_token,
            "rating": program_user.rating,
            "is_collected": program_user.is_collected
        })
    except Exception as e:
        return send_error_response_on_exception(e)


def collect_program(request, program_token=None):
    """
    收藏节目
    :param program_token: 节目标识
    """
    body = request.POST
    stb_id = body["stbid"]
    return _set_program_collect(program_token, stb_id, True)


def uncollect_program(request, program_token=None):
    """
    取消收藏节目
    :param request_token: 节目标识
    """
    body = request.POST
    stb_id = body["stbid"]
    return _set_program_collect(program_token, stb_id, False)


def _set_program_collect(program_token=None, stb_id=None, is_collect=False):
    try:
        program_user = _get_program_user_data(program_token=program_token, stb_id=stb_id)
        program_user.is_collected = is_collect
        program_user.save()
        return send_ok_response_with_data({
            "program": program_token,
            "operation": "program_collect" if is_collect else "program_uncollect",
            "isOk": True
        })
    except Exception as e:
        return send_error_response_on_exception(e)


def rating_program(request, program_token=None):
    """
    设置节目的星星数量
    :param program_token: 节目表示
    :param star_number: 星星个数
    """
    body = request.POST
    stb_id = body["stbid"]
    rating = int(body["rating"])
    try:
        program_user = _get_program_user_data(program_token=program_token, stb_id=stb_id)
        old_rating = program_user.rating
        rating_delta = rating - old_rating

        if rating_delta > 0:
            program_user.rating += rating_delta
            program_user.save()

            user = BengUserData.objects.get(stb_id=stb_id)
            user.rating_total += rating_delta
            user.save()

        return send_ok_response_with_data({
            "program": program_token,
            "operation": "program_rating",
            "isOk": True
        })
    except Exception as e:
        return send_error_response_on_exception(e)


def _get_program_user_data(program_token=None, stb_id=None):
    if not program_token:
        raise RuntimeError('界面标识为空')
    if not stb_id:
        raise RuntimeError('设备标识为空')

    try:
        user = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        raise e

    if not user:
        raise RuntimeError('无此设备 %s' % stb_id)

    try:
        program = BengProgram.objects.get(token=program_token)
    except Exception as e:
        raise e

    if not program:
        raise RuntimeError('无此媒体 %s' % program_token)

    program_user, created = BengProgramUserData.objects.get_or_create(program=program, user_data=user)
    return program_user


def is_unlocked(request, stb_id=None, program_token=None):
    """
    判断节目是否被解锁
    :param request:
    :param stb_id: 设备标识
    :param program_token: 节目token
    :return:
    """
    try:
        user_data = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        return send_error_response_on_exception(e)

    if not user_data:
        return send_error_response_with_message('无此用户')

    try:
        program = BengProgram.objects.get(token=program_token)
    except Exception as e:
        return send_error_response_on_exception(e)

    if not program:
        return send_error_response_with_message('无此节目')

    unlocked = user_data.unlock_programs
    unlocked = unlocked.split(',')

    if program_token in unlocked:
        return send_ok_response_with_data({
            "unlocked": True
        })
    else:
        return send_ok_response_with_data({
            "unlocked": False
        })


def _is_unlocked(stb_id=None, program_token=None):
    """
    判断节目是否被解锁
    :param stb_id: 设备标识
    :param program_token: 节目token
    :return:
    """
    try:
        user_data = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        return send_error_response_on_exception(e)

    if not user_data:
        return send_error_response_with_message('无此用户')

    try:
        program = BengProgram.objects.get(token=program_token)
    except Exception as e:
        return send_error_response_on_exception(e)

    if not program:
        return send_error_response_with_message('无此节目')

    unlocked = user_data.unlock_programs
    unlocked = unlocked.split(',')

    if program_token in unlocked:
        return True
    else:
        return False


def unlock_program(request, stb_id=None, program_token=None):
    """
    解锁单个新节目
    :param request:
    :return:
    """
    try:
        try:
            user_data = BengUserData.objects.get(stb_id=stb_id)
        except Exception as e:
            return send_error_response_on_exception(e)

        if not user_data:
            return send_error_response_with_message('无此用户')

        unlocked = user_data.unlock_programs

        try:
            program = BengProgram.objects.get(token=program_token)
        except Exception as e:
            return send_error_response_on_exception(e)

        if not program:
            return send_error_response_with_message('无此节目')

        unlocked = unlocked.split(',')
        star = user_data.rating_total

        new_unlock_list = list()
        last_unlock = None
        can_unlocked_count = int(star / 3)
        if can_unlocked_count:
            last_unlock = BengProgram.objects.get(token=unlocked[5])

        can_unlock_qs = BengProgram.objects.filter(id__gt=last_unlock.id, need_pay=False) # last_unlock已经解锁的第六个
        if can_unlock_qs.exists() and can_unlock_qs.count():
            if program in can_unlock_qs:
                unlocked.append(program_token)
                new_unlock_list.append(program_token)
            else:
                return send_error_response_with_message('该项目无法被解锁')
            user_data.unlock_programs = ','.join(unlocked)
            user_data.save()
            return send_ok_response_with_data({
                "newUnlock": new_unlock_list,
                "newUnlockCount": 1,
                "currentUnlock": unlocked
            })
        else:
            return send_error_response_with_message("解锁失败")
    except Exception as e:
        return send_error_response_on_exception(e)


def unlock_programs(request, stb_id=None):
    """
    解锁新节目
    """
    try:
        user_data = BengUserData.objects.get(stb_id=stb_id)
        unlocked = user_data.unlock_programs

        if not unlocked:
            return send_error_response_with_message('解锁项目为空')

        unlocked = unlocked.split(',')
        star = user_data.rating_total
        unlocked_count = len(unlocked)
        new_unlocked_count = int((star - (unlocked_count - 6) * 3) / 3)
        if new_unlocked_count:  # 如果可以解锁新项目
            last_unlock = None
            new_unlock_list = list()
            if unlocked_count:
                last_unlock = BengProgram.objects.get(token=unlocked[unlocked_count - 1])
            new_unlock_qs = BengProgram.objects.filter(id__gt=last_unlock.id)
            if new_unlock_qs.exists() and new_unlock_qs.count():  # 如果还有新项目可以解锁
                for new_unlock in new_unlock_qs[0:new_unlocked_count]:
                    unlocked.append(new_unlock.token)
                    new_unlock_list.append(new_unlock.token)
                user_data.unlock_programs = ",".join(unlocked)
                user_data.save()

            return send_ok_response_with_data({
                "newUnlock": new_unlock_list,
                "newUnlockCount": new_unlocked_count,
                "currentUnlock": unlocked
            })
        else:
            return send_error_response_with_message('没有可以解锁的项目')
    except Exception as e:
        return send_error_response_on_exception(e)


def pre_load_data(request):
    """
    预加载数据
    """
    body = request.POST
    body_keys = body.keys()
    version_type = None
    version_code = None
    if "md5" in body_keys:
        version_type = "md5"
        version_code = body["md5"]
    elif "sha1" in body_keys:
        version_type = "sha1"
        version_code = body["sha1"]

    try:
        last_version = BengVersion.objects.last()
    except Exception as e:
        return send_error_response_on_exception(e)

    version = None
    if version_code:
        try:
            version = BengVersion.objects.get(**{version_type: version_code})
        except Exception as e:
            return send_error_response_on_exception(e)
        if not version:
            return send_error_response_with_message('无此版本 %s' % version_code)

    if version:
        if last_version.id == version.id:
            return send_ok_response_with_data({
                "update": False
            })

        package_qs = BengPackage.objects.filter(date_added__gt=version.date_added)
    else:
        package_qs = BengPackage.objects.filter()
    try:
        if package_qs.count():
            package_list = list()
            for package in package_qs:
                program = BengProgram.objects.get(token=package.program_token)
                if program.is_invalid:
                    continue

                package_list.append({
                    "token": package.program_token,
                    "url": package.url
                })
            if len(package_list):
                return send_ok_response_with_data({
                    "update": True,
                    "versionMd5": last_version.md5,
                    "versionSha1": last_version.sha1,
                    "packages": package_list
                })

        return send_ok_response_with_data({
            "update": False
        })

    except Exception as e:
        return send_error_response_on_exception(e)


def switch_user(request, stb_id=None):

    body = None
    if request.method == 'GET':
        body = request.GET

    if "versionname" in body:
        req = urllib2.Request('http://121.201.14.248/bbt_weixin/data.jsp?userId=%s' % stb_id)
    else:
        req = urllib2.Request('http://121.201.14.248/wanba/data.jsp?userId=%s' % stb_id)
    res = urllib2.urlopen(req)
    res_content = res.read()
    res.close()
    res_obj = json.loads(res_content, encoding='utf-8')

    if "qrUrl" not in res_obj.keys():
        return send_error_response_with_message('切换账户未成功')

    return send_ok_response_with_data({
        "qr": res_obj["qrUrl"]
    })


def notify_payed_program(request):
    body = request.POST
    import logging
    logger = logging.getLogger("wanba")
    logger.info('Notify from payed: %s' % (json.dumps(request.POST)))
    stb_id = body["stbid"]
    subjectid = body["subjectid"]
    dateexpire = body["dateexpire"]
    expiretime_array = time.strptime(dateexpire, "%Y-%m-%d %H:%M:%S")
    dateexpire = time.strftime("%Y%m%d%H%M%S", expiretime_array)
    new_payed_programs = list()

    try:
        subject = Subject.objects.get(code=subjectid)
        user = BengUserData.objects.get(stb_id=stb_id)
        program = BengProgram.objects.get(subject=subject)
        payed_programs = user.payed_programs
        payed_programs = payed_programs.split(',')
        # 如果节目已经购买，则更新截止日期
        for payed_program in payed_programs:
            if program.token==payed_program:
                new_payed_programs.append(program.token+dateexpire)
            else:
                new_payed_programs.append(payed_program)
        # 如果未购买过
        if (program.token+dateexpire) not in new_payed_programs:
            new_payed_programs.append(program.token+dateexpire)
        user.payed_programs = ','.join(new_payed_programs)
        user.save()
        return send_ok_response_with_data({
            "success": True,
        })
    except Exception as e:
        return send_error_response_on_exception(e)




def login(request):
    """
    登录并初始化
    """
    body = request.POST
    stb_id = body["stbid"]
    try:
        user, created = BengUserData.objects.get_or_create(stb_id=stb_id)
        if created and not user.unlock_programs:
            # 如果是新建的用户，默认解锁六个节目
            try:
                program_qs = BengProgram.objects.filter(is_invalid=False, need_pay=False)  # 添加是否需要付费过滤
                if program_qs.exists():
                    unlock_items = list()
                    for program in program_qs[0:6]:
                        unlock_items.append(program.token)
                    user.unlock_programs = ",".join(unlock_items)
                    user.save()
            except Exception as e:
                return send_error_response_on_exception(e)

        if "versionname" in body:
            req = urllib2.Request('http://121.201.14.248/bbt_weixin/data.jsp?userId=%s' % stb_id)
        else:
            req = urllib2.Request('http://121.201.14.248/wanba/data.jsp?userId=%s' % stb_id)
        res = urllib2.urlopen(req)
        res_content = res.read()
        res.close()
        res_obj = json.loads(res_content, encoding='utf-8')

        qr_url = res_obj["qrUrl"] if "qrUrl" in res_obj.keys() else ''
        wx_user_id = user.wx_user_id
        wx_nick_name = user.wx_nickname
        wx_avatar = ''
        if wx_user_id:
            wx_avatar = user.wx_avatar
            if "userList" in res_obj.keys():
                user_list = res_obj["userList"]
                for user_item in user_list:
                    if user_item["weixinId"] == user.wx_user_id:
                        if user_item["avatar"] != user.wx_avatar or user_item["nickName"] != user.wx_nickname:
                            wx_avatar = user_item["avatar"]
                            wx_nick_name = user_item["nickName"]
                            user.wx_avatar = wx_avatar
                            user.wx_nickname = wx_nick_name
                            user.save()
                        break

        # 绑定推送服务器
        if user.wx_user_id:
            _bind_user_data(stb_id, user.wx_user_id, user.wx_avatar, user.wx_nickname)

        return send_ok_response_with_data({
            "wxUserId": wx_user_id,
            "wxNickname": wx_nick_name,
            "wxAvatar": wx_avatar,
            "qr": qr_url,
            "unlocks": user.unlock_programs.split(",") if user.unlock_programs else []
        })
    except Exception as e:
        return send_error_response_on_exception(e)


def binds_weixin_user_data(request):
    """
    绑定微信数据到客户端
    """
    body = request.POST
    stb_id = body["stb"]
    wx_user_id = body["wxuserid"]
    wx_avatar = body["wxavatar"]
    wx_nickname = body["wxnickname"]

    import logging
    logger = logging.getLogger("wanba")
    logger.info('binds_weixin_user_data POST %s' % json.dumps(body))

    return send_response_with_result(_bind_user_data(stb_id, wx_user_id, wx_avatar, wx_nickname))


def _bind_user_data(stb_id, wx_user_id, wx_avatar, wx_nickname):
    try:
        user_data = BengUserData.objects.get(stb_id=stb_id)
        user_data.wx_user_id = wx_user_id
        user_data.wx_avatar = wx_avatar
        user_data.wx_nickname = wx_nickname
        user_data.save()

    except Exception as e:
        return send_error_response_on_exception(e)

    from wanpuzzle.models.common import Application
    try:
        app_model = Application.objects.get(package="com.wanbatv.wanba.ott")
    except Exception as e:
        return send_error_response_on_exception(e)

    post_data = dict()
    post_data["app"] = app_model.token + "_" + app_model.sign_key
    post_data["client"] = stb_id
    post_data["group"] = wx_user_id
    post_data["api"] = "wanba.ott.user.bind"
    post_data["data"] = json.dumps({
        "userid": wx_user_id,
        "avatar": wx_avatar,
        "nickname": wx_nickname
    })

    from wanbatvapp.settings import MESSENGER_HOST
    req = urllib2.Request('http://%s/posthouse/bind' % MESSENGER_HOST, data=urllib.urlencode(post_data))
    res = urllib2.urlopen(req)
    content = res.read()
    res.close()

    return content


def add_weixin_user_media(request):
    body = request.POST
    data = {
        "src": body["mediasrc"],
        "mediaType": body["mediatype"],
        "iconSrc": body["iconsrc"],
        "avatar": body["wxavatar"],
        "uploadDate": body["date"],
        "mediaId": body["mediaid"],
    }
    date = data["uploadDate"]
    if date.find("-") < 0:
        temp_date = datetime.datetime.strptime(date, "%Y%m%d")
        data["uploadDate"] = temp_date.strftime("%Y-%m-%d")

    return _notify_result_group(request, "wanba.ott.baby.add", request.POST["wxuserid"], data)


def _notify_result_group(request, tag=None, group=None, data=None):
    from wanpuzzle.models.common import Application
    try:
        app_model = Application.objects.get(package="com.wanbatv.wanba.ott")
    except Exception as e:
        return send_error_response_on_exception(e)

    if not group:
        return send_error_response_with_message(message='缺少参数 client')

    post_data = dict()
    post_data["app"] = app_model.token + "_" + app_model.sign_key
    post_data["group"] = group
    post_data["api"] = tag
    post_data["data"] = json.dumps(data if data else request.POST.copy())

    from wanbatvapp.settings import MESSENGER_HOST
    req = urllib2.Request('http://%s/posthouse/notify/group' % MESSENGER_HOST, data=urllib.urlencode(post_data))
    res = urllib2.urlopen(req)
    content = res.read()
    res.close()

    return send_response_with_result(content)


def sync_program(request, program_token):
    """
    保存平台的节目数据到api
    :param request:
    :return:
    """
    body = request.POST

    try:
        program, created = BengProgram.objects.get_or_create(token=program_token)
        program.title = body["title"]
        program.bgm = body["bgm"]
        program.media = body["media"]
        program.cover_n_hd = body["covernhd"]
        program.cover_h_fg_hd = body["coverhfghd"]
        # program.cover_h_bg_hd = body["coverhbghd"]
        program.cover_n_fhd = body["covernfhd"]
        program.cover_h_fg_fhd = body["coverhfgfhd"]
        # program.cover_h_bg_fhd = body["coverhbgfhd"]
        program.save()

        timestamp = time.time()
        md5 = hashlib.md5()
        md5.update("{}{}".format(program_token, timestamp))
        pkg_token = md5.hexdigest()

        package, created = BengPackage.objects.get_or_create(program_token=program_token)
        package.token = pkg_token
        package.url = body["wrpurl"]
        package.save()

        # 生成版本的MD5和sha1
        md5 = hashlib.md5()
        md5.update("{}{}".format(pkg_token, timestamp))
        sha1 = hashlib.sha1()
        sha1.update("{}{}".format(pkg_token, timestamp))

        # 更新版本号
        version = BengVersion()
        version.md5 = md5.hexdigest()
        version.sha1 = sha1.hexdigest()
        version.save()

        return send_ok_response_with_data({
            "token": program_token,
            "syncOk": True
        })
    except Exception as e:
        return send_error_response_on_exception(e)


def is_like(request):
    body = request.POST
    stbid = body["stbid"]
    itemid = body["itemId"]
    if not stbid:
        return send_error_response_with_message("设备为空")

    if not itemid:
        return send_error_response_with_message("分享为空")

    try:
        user = BengUserData.objetcs.get(stb_id=stbid)
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
        media = BengShared.objects.get(id=itemid)
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
        # 查询用户是否已经点过赞，避免重复点赞
        like_model = BengSharedLike.objects.filter(media_like=media, user_like=user).count()
        if like_model:
            return send_ok_response_with_data({"isLike": True})
        else:
            return send_ok_response_with_data({"isLike": False})
    except Exception as e:
        return send_error_response_on_exception(e)


def get_shared_list(request):
    """
    获取分享列表
    :param request:
    :return:
    """
    stbid = None
    if request.method == 'POST':
        body = request.POST
        if 'stbid' in body:
            stbid = body['stbid']

    try:
        shared_qs = BengShared.objects.order_by("-date_added").filter(is_invalid=False)
        if shared_qs.exists() and shared_qs.count():
            shared_list = list()
            # activity = True
            # if activity:
            #     activity_url = 'http://192.168.31.211:28085/'
            #     activity_img = 'http://121.201.7.173:28085/20160614/imgs/usercenter.png'
            #     activity_name = '20160614'
            #     activity_photo_frame = ''
            #     shared_list.append({
            #         "activityUrl": activity_url,
            #         "activityImg": activity_img,
            #         "activityName": activity_name,
            #         "photoFrame": activity_photo_frame,
            #     })
            for shared_item in shared_qs:
                like_users = BengSharedLike.objects.filter(media_like=shared_item)
                like_user_list = list()
                isLike = False
                for like_user in like_users:
                    if stbid == like_user.user_like.stb_id:
                        isLike = True
                    like_user_list.append({
                        "stbid": like_user.user_like.stb_id,
                        "wxAvatar": like_user.user_like.wx_avatar,
                    })

                shared_list.append({
                    "itemId": shared_item.id,
                    "mediaId": shared_item.media_id,
                    "mediaType": shared_item.media_type,
                    "mediaSrc": shared_item.media_url,
                    "iconSrc": shared_item.cover_url,
                    "date": str(shared_item.date_added)[:10],
                    "wxUserId": shared_item.pub_wx_user_id,
                    "wxNickname": shared_item.pub_wx_nickname,
                    "wxAvatar": shared_item.pub_wx_avatar,
                    "likeNum": shared_item.like_num,
                    "likeUsers": like_user_list,
                    "isLike": isLike,
                })
            return send_ok_response_with_list(shared_list)
        else:
            return send_ok_response_with_list([], message='分享列表为空')
    except Exception as e:
        return send_error_response_on_exception(e)


def get_like_users(request):
    body = request.GET
    item_id = body["itemid"]

    try:
        media = BengShared.objects.get(id=item_id)
        like_users = BengSharedLike.objects.filter(media_like=media)
        like_user_list = list()

        for like_user in like_users:
            like_user_list.append({
                "stbid": like_user.user_like.stb_id,
                "wxAvatar": like_user.user_like.wx_avatar,
            })
        return send_ok_response_with_data({
            "likeUsers": like_user_list,
        })
    except Exception as e:
        return send_error_response_on_exception(e)


def get_shared_list_activity(request):
    """
    获取活动分享列表
    :param request:
    :return:
    """
    body = request.POST

    try:
       # shared_qs = list()
        if 'lastid' in body:
            lastid = body['lastid']
            shared_qs = BengShared.objects.order_by("-date_added").filter(is_invalid=False,
                                                                          status=1,
                                                                          media_type='video',
                                                                          id__gt=lastid)
        else:
            shared_qs = BengShared.objects.order_by("-date_added").filter(is_invalid=False, status=1, media_type="video")
        if 'limit' in body:
           limit = body['limit']
           shared_qs = shared_qs[0:limit]

        if shared_qs.exists() and shared_qs.count():
            shared_list = list()

            for shared_item in shared_qs:
                like_users = BengSharedLike.objects.filter(media_like=shared_item)
                like_user_list = list()
                stbid = None
                isLike = False
                if 'stbid' in body:
                    stbid = body['stbid']
                for like_user in like_users:
                    if stbid == like_user.user_like.stb_id:
                        isLike = True
                    like_user_list.append({
                        "stbid": like_user.user_like.stb_id,
                        "wxAvatar": like_user.user_like.wx_avatar,
                    })

                shared_list.append({
                    "itemId": shared_item.id,
                    "mediaId": shared_item.media_id,
                    "mediaSrc": shared_item.media_url,
                    "iconSrc": shared_item.cover_url,
                    "wxAvatar": shared_item.pub_wx_avatar,
                    "likeNum": shared_item.like_num,
                })
            return send_ok_response_with_list(shared_list)
        else:
            return send_ok_response_with_list([], message='分享列表为空')
    except Exception as e:
        return send_error_response_on_exception(e)


def activity_get(request):
    body = request.GET
    flavor = body["flavor"]
    # url = 'http://121.201.14.248:28085/'
    # name = '儿童舞大赛'
    # img = 'http://121.201.14.248:28085/20160614/imgs/usercenter.png'
    # photoframe = ''
    activity = BengActivity.objects.get(id=1)

    return send_ok_response_with_data({
        "activityUrl": activity.activity_url,
        "isActivity": activity.activity,
        "activityName": activity.activity_name,
        "activityImg": activity.activity_img,
        "photoframe": activity.activity_photoFrame,
    })


def get_shared_list_deleted(request):
    """
    获取已下架的分享列表
    :param request:
    :return:
    """
    if request.method == 'POST':
        body = request.POST

    try:
        shared_qs = BengShared.objects.order_by("-id").filter(is_invalid=True)
        if shared_qs.exists() and shared_qs.count():
            shared_list = list()
            for shared_item in shared_qs:
                like_users = BengSharedLike.objects.filter(media_like=shared_item)
                like_user_list = list()
                stbid = None
                isLike = False
                if 'stbid' in body:
                    stbid = body['stbid']
                for like_user in like_users:
                    if stbid == like_user.user_like.stb_id:
                        isLike = True
                    like_user_list.append({
                        "stbid": like_user.user_like.stb_id,
                        "wxAvatar": like_user.user_like.wx_avatar,
                    })

                shared_list.append({
                    "itemId": shared_item.id,
                    "mediaId": shared_item.media_id,
                    "mediaType": shared_item.media_type,
                    "mediaSrc": shared_item.media_url,
                    "iconSrc": shared_item.cover_url,
                    "date": str(shared_item.date_added)[:10],
                    "wxUserId": shared_item.pub_wx_user_id,
                    "wxNickname": shared_item.pub_wx_nickname,
                    "wxAvatar": shared_item.pub_wx_avatar,
                    "likeNum": shared_item.like_num,
                    "likeUsers": like_user_list,
                    "isLike": isLike,
                })
            return send_ok_response_with_list(shared_list)
        else:
            return send_ok_response_with_list([], message='分享列表为空')
    except Exception as e:
        return send_error_response_on_exception(e)


def get_photo_frame(request):
    activity = True
    frameUrl = ""
    if activity:
        frameUrl=""
        return send_ok_response_with_data({
            "frameUrl": frameUrl,
            "activity": True,
        })
    else:
        return send_ok_response_with_data({
            "frameUrl": frameUrl,
            "activity": False,
        })


def shared_user_picture(request, stb_id=None):
    """
    分享用户宝贝空间的内容
    :param request:
    :return:
    """
    body = request.POST
    import logging
    logger = logging.getLogger('wanba')
    logger.info('shared from %s', body)
    try:
        user_data = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        return send_error_response_on_exception(e)

    shared_data = body["shareds"]
    shared_json = json.loads(shared_data, encoding='utf-8')
    shared_list = shared_json["shareds"]

    for shared_item in shared_list:
        try:
            shared_item_model, created = BengShared.objects.get_or_create(media_id=shared_item["mediaid"])
            shared_item_model.media_type = shared_item["mediatype"]
            shared_item_model.media_url = shared_item["mediasrc"]
            shared_item_model.cover_url = shared_item["iconsrc"]
            shared_item_model.publish_date = shared_item["date"]
            if "wxuserid" in shared_item.keys():
                shared_item_model.pub_wx_user_id = shared_item["wxuserid"]
            if "wxnickname" in shared_item.keys():
                shared_item_model.pub_wx_nickname = shared_item["wxnickname"]
            if "wxavatar" in shared_item.keys():
                shared_item_model.pub_wx_avatar = shared_item["wxavatar"]
            if "activity" in shared_item.keys():
                shared_item_model.status = 1
            shared_item_model.shd_wx_user_id = user_data.wx_user_id
            shared_item_model.shd_wx_nickname = user_data.wx_nickname
            shared_item_model.shd_wx_avatar = user_data.wx_avatar
            shared_item_model.stb = stb_id
            shared_item_model.save()
        except Exception as e:
            return send_error_response_on_exception(e)

    return send_ok_response_with_data({
        "operation": "baby_shared",
        "isOk": True
    })


def get_baby_self_list(request, stb_id=None):
    req = urllib2.Request('http://121.201.14.248/wanba/data.jsp?userId=%s' % stb_id)
    res = urllib2.urlopen(req)
    res_content = res.read()
    res.close()
    res_obj = json.loads(res_content, encoding='utf-8')

    reqnew = urllib2.Request('http://121.201.14.248/bbt_weixin/data.jsp?userId=%s' % stb_id)
    resnew = urllib2.urlopen(reqnew)
    resnew_content = resnew.read()
    resnew.close()
    resnew_obj = json.loads(resnew_content, encoding='utf-8')

    medialist = list()

    if "mediaList" in resnew_obj.keys():
        if resnew_obj["mediaList"]:
            for media_node in resnew_obj["mediaList"]:
                mediaid = media_node["mediaId"]
                print mediaid
                media = BengShared.objects.filter(media_id=mediaid).count()
                if media:
                    media_node["isShared"] = True
                else:
                    media_node["isShared"] = False
                medialist.append(media_node)

    if "mediaList" in res_obj.keys():
        if res_obj["mediaList"]:
            for media_node in res_obj["mediaList"]:
                mediaid = media_node["mediaId"]
                print mediaid
                media = BengShared.objects.filter(media_id=mediaid).count()
                if media:
                    media_node["isShared"] = True
                else:
                    media_node["isShared"] = False
                medialist.append(media_node)

    return send_ok_response_with_data({
        # "mediaList": res_obj["mediaList"] if "mediaList" in res_obj.keys() else []
        "mediaList": medialist if medialist else []
    })


def admin_delete_baby(request, itemid=None):
    if itemid:
        try:
            media = BengShared.objects.get(id=itemid)
        except Exception as e:
            return send_error_response_on_exception(e)

        media.is_invalid = 1
        media.save()
        try:
            shared_qs = BengShared.objects.order_by("-id").filter(is_invalid=False)
            if shared_qs.exists() and shared_qs.count():
                shared_list = list()
                for shared_item in shared_qs:
                    # like_users = BengSharedLike.objects.filter(media_like=shared_item.id)
                    # like_user_list = list()
                    # for like_user in like_users:
                    #     like_user_list.append({
                    #         "stbid": like_user.stb_id,
                    #         "wxAvatar": like_user.wx_avatar,
                    #     })
                    shared_list.append({
                        "itemId": shared_item.id,
                        "mediaId": shared_item.media_id,
                        "mediaType": shared_item.media_type,
                        "mediaSrc": shared_item.media_url,
                        "iconSrc": shared_item.cover_url,
                        "date": str(shared_item.date_added)[:10],
                        "wxUserId": shared_item.pub_wx_user_id,
                        "wxNickname": shared_item.pub_wx_nickname,
                        "wxAvatar": shared_item.pub_wx_avatar,
                        "likeNum": shared_item.like_num,
                        # "likeUsers": like_user_list,
                    })
                return send_ok_response_with_list(shared_list)
            else:
                return send_ok_response_with_list([], message='分享列表为空')
        except Exception as e:
            return send_error_response_on_exception(e)
    else:
        return send_error_response_with_message("没有对应的媒体资源")


def admin_recovery_baby(request, itemid=None):
    if itemid:
        try:
            media = BengShared.objects.get(id=itemid)
        except Exception as e:
            return send_error_response_on_exception(e)

        media.is_invalid = 0
        media.save()
        try:
            shared_qs = BengShared.objects.order_by("-id").filter(is_invalid=False)
            if shared_qs.exists() and shared_qs.count():
                shared_list = list()
                for shared_item in shared_qs:
                    # like_users = BengSharedLike.objects.filter(media_like=shared_item.id)
                    # like_user_list = list()
                    # for like_user in like_users:
                    #     like_user_list.append({
                    #         "stbid": like_user.stb_id,
                    #         "wxAvatar": like_user.wx_avatar,
                    #     })
                    shared_list.append({
                        "itemId": shared_item.id,
                        "mediaId": shared_item.media_id,
                        "mediaType": shared_item.media_type,
                        "mediaSrc": shared_item.media_url,
                        "iconSrc": shared_item.cover_url,
                        "date": str(shared_item.date_added)[:10],
                        "wxUserId": shared_item.pub_wx_user_id,
                        "wxNickname": shared_item.pub_wx_nickname,
                        "wxAvatar": shared_item.pub_wx_avatar,
                        "likeNum": shared_item.like_num,
                        # "likeUsers": like_user_list,
                    })
                return send_ok_response_with_list(shared_list)
            else:
                return send_ok_response_with_list([], message='分享列表为空')
        except Exception as e:
            return send_error_response_on_exception(e)
    else:
        return send_error_response_with_message("没有对应的媒体资源")


def delete_baby(request, stb_id=None):
    body = request.POST
    video_ids = None
    image_ids = None
    if 'videos' in body.keys():
        video_ids = body["videos"].split(",")
    if 'images' in body.keys():
        image_ids = body["images"].split(",")

    query = []
    if video_ids:
        try:
            BengShared.objects.filter(media_id__in=video_ids, stb=stb_id, media_type='video').update(is_invalid=True)
        finally:
            pass
        query.append('videoMediaIds=%s' % body["videos"])

    if image_ids:
        try:
            BengShared.objects.filter(media_id__in=image_ids, stb=stb_id, media_type='img').update(is_invalid=True)
        finally:
            pass
        query.append('imgMediaIds=%s' % body["images"])

    if query:
        req = urllib2.Request('http://121.201.14.248/wanba/batchDelete.jsp?%s' % '&'.join(query))
        res = urllib2.urlopen(req)
        res_content = res.read()
        res_content = res_content.replace('\r\n', '')
        res_content = res_content.replace('\t', '')
        res.close()

        reqnew = urllib2.Request('http://121.201.14.248/bbt_weixin/batchDelete.jsp?%s' % '&'.join(query))
        resnew = urllib2.urlopen(reqnew)
        resnew_content = resnew.read()
        resnew_content = resnew_content.replace('\r\n', '')
        resnew_content = resnew_content.replace('\t', '')
        resnew.close()

        return send_ok_response_with_data({
            "operation": 'baby_delete',
            "isOk": res_content == 'true' or resnew_content == 'true'
        })
    else:
        return send_error_response_with_message('没有需要删除的项目')


def activity_like(request):
    body = request.POST
    user = body['stbid']
    times = 1
    if "times" in body:
        times = int(body["times"])
    if not user:
        return send_error_response_with_message("设备为空")
    media = body['itemid']
    if not media:
        return send_error_response_with_message("媒体为空")
    try:
        media_data = BengShared.objects.get(id=media)
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
        user_data = BengUserData.objects.get(stb_id=user)
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
        activity_model, create = BengActivityLike.objects.get_or_create(activity_user=user_data)

    except Exception as e:
        return send_error_response_on_exception(e)

    lastlike = activity_model.activity_time
    today_date = datetime.datetime.now()
    today = str(today_date)[0:10]
    if activity_model.activity_time:
        if today == lastlike:
            if activity_model.activity_likenum + times < 10:

                activity_model.activity_likenum += times
                activity_model.save()

                media_data.like_num += times
                media_data.save()
                return send_ok_response_with_data({
                    "canLike": True,
                    "likeNum": media_data.like_num,
                })
            else:
                media_data.like_num += (10 - activity_model.activity_likenum)
                media_data.save()

                activity_model.activity_likenum = 10
                activity_model.save()

                return send_ok_response_with_data({
                    "canLike": False,
                    "likeNum": media_data.like_num,
                })
        else:
            if times < 10:
                activity_model.activity_likenum = times
                activity_model.activity_time = today
                activity_model.save()

                media_data.like_num += times
                media_data.save()
                return send_ok_response_with_data({
                    "canLike": True,
                    "likeNum": media_data.like_num,
                })
            else:
                media_data.like_num += 10
                media_data.save()

                activity_model.activity_likenum = 10
                activity_model.activity_time = today
                activity_model.save()

                return send_ok_response_with_data({
                    "canLike": True,
                    "likeNum": media_data.like_num,
                })
    else:
        activity_model.activity_likenum = 1
        activity_model.activity_time = today
        activity_model.save()

        media_data.like_num += 1
        media_data.save()
        return send_ok_response_with_data({
            "canLike": True
        })


def like_shared(request):
    body = request.POST
    user = body['stbid']
    if not user:
        return send_error_response_with_message("设备为空")
    item = body['itemid']
    if not item:
        return send_error_response_with_message("媒体为空")

    try:
        media_data = BengShared.objects.get(id=item)
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
        user_data = BengUserData.objects.get(stb_id=user)
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
        # 查询用户是否已经点过赞，避免重复点赞
        like_model = BengSharedLike.objects.filter(media_like=media_data, user_like=user_data).count()
        if like_model:
            like_users = BengSharedLike.objects.filter(media_like=media_data.id)
            like_user_list = list()
            for like_user in like_users:
                like_user_list.append({
                    "stbid": like_user.user_like.stb_id,
                    "wxAvatar": like_user.user_like.wx_avatar,
                })
            return send_ok_response_with_data({
                                            # 'success': '点赞成功',
                                            'likeNum': media_data.like_num,
                                            'likeUsers': like_user_list,
                                            'successLike': False,
            })
        else:
            like_model = BengSharedLike()
            like_model.user_like = user_data
            like_model.media_like = media_data
            like_model.save()

            media_data.like_num += 1
            media_data.save()

            like_users = BengSharedLike.objects.filter(media_like=media_data.id)
            like_user_list = list()
            for like_user in like_users:
                like_user_list.append({
                    "stbid": like_user.user_like.stb_id,
                    "wxAvatar": like_user.user_like.wx_avatar,
                })
            return send_ok_response_with_data({
                                            # 'success': '点赞成功',
                                            'likeNum': media_data.like_num,
                                            'likeUsers': like_user_list,
                                            'successLike': True,
            })
    except Exception as e:
        return send_error_response_on_exception(e)


def unlike_shared(request):
    body = request.POST
    user = body['stbid']
    if not user:
        return send_error_response_with_message("设备为空")
    item = body['itemid']
    if not item:
        return send_error_response_with_message("媒体为空")

    try:
        media_data = BengShared.objects.get(id=item)
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
        user_data = BengUserData.objects.get(stb_id=user)
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
        like_model = BengSharedLike.objects.get(media_like=media_data.id, user_like=user_data.id)
        like_model.delete()
        # 点赞数减一
        media_data.like_num -= 1
        media_data.save()
        return send_response_with_result("{'success' : '取消赞'}")
    except Exception as e:
        return send_error_response_on_exception(e)


def activity_top10(request):
    if request.method == 'POST':
        body = request.POST

    try:
        shared_qs = BengShared.objects.order_by("-like_num").filter(is_invalid=False, status=1, media_type="video")[:10]
        if shared_qs.exists() and shared_qs.count():
            shared_list = list()

            for shared_item in shared_qs:
                like_users = BengSharedLike.objects.filter(media_like=shared_item)
                like_user_list = list()
                stbid = None
                isLike = False
                if 'stbid' in body:
                    stbid = body['stbid']
                for like_user in like_users:
                    if stbid == like_user.user_like.stb_id:
                        isLike = True
                    like_user_list.append({
                        "stbid": like_user.user_like.stb_id,
                        "wxAvatar": like_user.user_like.wx_avatar,
                    })

                shared_list.append({
                    "itemId": shared_item.id,
                    # "mediaId": shared_item.media_id,
                    # "mediaType": shared_item.media_type,
                    "mediaSrc": shared_item.media_url,
                    "iconSrc": shared_item.cover_url,
                    # "date": str(shared_item.date_added)[:10],
                    # "wxUserId": shared_item.pub_wx_user_id,
                    # "wxNickname": shared_item.pub_wx_nickname,
                    "wxAvatar": shared_item.pub_wx_avatar,
                    "likeNum": shared_item.like_num,
                    # "likeUsers": like_user_list,
                    # "isLike": isLike,
                })
            return send_ok_response_with_list(shared_list)
        else:
            return send_ok_response_with_list([], message='分享列表为空')
    except Exception as e:
        return send_error_response_on_exception(e)


def activity_new_programs(request, page='1'):
    page_num = int(page)
    host = request.get_host()
    if request.method == 'POST':
        body = request.POST

    try:
        shared_qs = BengShared.objects.order_by("-date_added").filter(is_invalid=False,
                                                                      status=1,
                                                                      media_type="video")[(page_num-1)*8:(page_num-1)*8 + 8]
        count = BengShared.objects.filter(is_invalid=False, status=1, media_type="video").count()
        if shared_qs.exists() and shared_qs.count():
            shared_list = list()
            # preurl = None
            # nexturl = None

            for shared_item in shared_qs:
                like_users = BengSharedLike.objects.filter(media_like=shared_item)
                like_user_list = list()
                stbid = None
                isLike = False
                if 'stbid' in body:
                    stbid = body['stbid']
                for like_user in like_users:
                    if stbid == like_user.user_like.stb_id:
                        isLike = True
                    like_user_list.append({
                        "stbid": like_user.user_like.stb_id,
                        "wxAvatar": like_user.user_like.wx_avatar,
                    })

                shared_list.append({
                    "itemId": shared_item.id,
                    # "mediaId": shared_item.media_id,
                    # "mediaType": shared_item.media_type,
                    "mediaSrc": shared_item.media_url,
                    "iconSrc": shared_item.cover_url,
                    # "date": str(shared_item.date_added)[:10],
                    # "wxUserId": shared_item.pub_wx_user_id,
                    # "wxNickname": shared_item.pub_wx_nickname,
                    "wxAvatar": shared_item.pub_wx_avatar,
                    "likeNum": shared_item.like_num,
                    #"likeUsers": like_user_list,
                    #"isLike": isLike,
                })

            if page_num * 8 <= count:
                nexturl = "http://%s/api/bengbengtiao/activity/programs/%s" % (host, page_num+1)
            else:
                nexturl = ""
            if page_num != 1:
                preurl = "http://%s/api/bengbengtiao/activity/programs/%s" % (host, page_num-1)
            else:
                preurl = ""

            return send_ok_response_with_data({
                "preUrl": preurl,
                "nextUrl": nexturl,
                "sharedList": shared_list,
            })
        else:
            return send_ok_response_with_list([], message='分享列表为空')
    except Exception as e:
        return send_error_response_on_exception(e)


def get_qrcode(request):

    body = request.POST
    stb_id = body["stbid"]
    req = urllib2.Request('http://121.201.14.248/bbt_weixin/data.jsp?userId=%s' % stb_id)
    res = urllib2.urlopen(req)
    res_content = res.read()
    res.close()
    res_obj = json.loads(res_content, encoding='utf-8')

    if "qrUrl" not in res_obj.keys():
        return send_error_response_with_message('二维码获取失败')

    return send_ok_response_with_data({
        "qr": res_obj["qrUrl"]
    })


def activity_init(request):
    # body = request.POST
    # stb_id = body["stbid"]
    body = request.POST
    user = body['stbid']

    if not user:
        return send_error_response_with_message("设备为空")

    try:
        user_data = BengUserData.objects.get(stb_id=user)
    except Exception as e:
        return send_error_response_on_exception(e)
    try:
        activity = BengActivity.objects.get(id=1)
        activity.activityTimes += 1
        activity.save()
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
       activity_model, create = BengActivityLike.objects.get_or_create(activity_user=user_data)
       lastlike = activity_model.activity_time
       today_date = datetime.datetime.now()
       today = str(today_date)[0:10]
       if today != lastlike:
           activity_model.activity_time = today
           activity_model.activity_likenum = 0
           activity_model.save()
    # try:
    #     user = BengUserData.objects.get(stb_id=stb_id)
    except Exception as e:
        return send_error_response_on_exception(e)

    # try:
    #     activityLike = BengActivityLike.objects.get(activity_user=user)
    # except Exception as e:
    #     return  send_error_response_on_exception(e)

    return send_ok_response_with_data({
        "canLikeNum": 10 - activity_model.activity_likenum,
    })
